package net.begincode.maiev.monitor.http;

import com.fasterxml.jackson.core.type.TypeReference;
import net.begincode.maiev.enums.StatusFlagEnum;
import net.begincode.maiev.handler.MonitorProjectHandler;
import net.begincode.maiev.model.MonitorProject;
import net.begincode.maiev.util.JsonUtils;
import net.begincode.maiev.util.SpringApplicationContextHolder;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Created by Stay on 2017/3/18  14:22.
 */
public class HttpGrab {
    private static Logger logger = LoggerFactory.getLogger(HttpGrab.class);

    public static <T> T send(Integer projectId, String url, TypeReference<T> typeReference) {
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        T value = null;
        String jsonData = null;
        try {
            HttpGet get = new HttpGet(url);
            response = client.execute(get);
            updateMonitorProjectStatus(Integer.parseInt(StatusFlagEnum.NORMAL_STATUS.getCode()), projectId);
            Header[] headers = response.getAllHeaders();
            for(Header head : headers){
                if(head.getValue().equals("application/json;charset=utf-8")){
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        jsonData = EntityUtils.toString(entity, "UTF-8");
                        logger.debug(jsonData);
                    }
                    value = JsonUtils.decode(jsonData.toString(), typeReference);
                    logger.debug(value.toString());
                }
            }
        } catch (IOException e) {
            updateMonitorProjectStatus(Integer.parseInt(StatusFlagEnum.ABNORMAL_STATUS.getCode()), projectId);
//            logger.error(e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return value;
    }

    private static void updateMonitorProjectStatus(Integer status, Integer projectId) {
        MonitorProject project = new MonitorProject();
        project.setId(projectId);
        project.setProjectStatus(status);
        MonitorProjectHandler monitorProjectHandler = (MonitorProjectHandler) SpringApplicationContextHolder.getSpringBean("monitorProjectHandler");
        monitorProjectHandler.updateMonitorProjectStatus(project);
    }


}
